import { isFunction } from 'lodash-es'

export function usernameValidator(
  value: any,
  callback: (error?: string | undefined) => void,
) {
  const reg = /^(?!\d*$)\w{4,18}$/

  if (!value) {
    callback('请输入账号')
  } else if (!reg.test(value)) {
    callback('请输入4-18个字符，可包含英文字母、数字、下划线，不能为纯数字')
  } else {
    callback()
  }
}

export function passwordValidate(
  value: any,
  callback: any,
  affterFn?: () => void,
  reset: boolean = false,
) {
  const reg1 = /^\S{6,64}$/

  // eslint-disable-next-line no-control-regex
  const reg2 = /[^\x00-\xFF]/

  if (!value) {
    const text = reset ? '请输入新密码' : '请输入密码'
    callback(text)
  } else if (!reg1.test(value) || reg2.test(value)) {
    callback('请输入6-64个字符，可包含英文字母、数字和标点符号（除空格）')
  } else {
    callback()
  }
  if (affterFn && isFunction(affterFn)) {
    affterFn()
  }
}

/** 邮箱验证 */
export function emailValidate(
  value: any,
  callback: (error?: string) => void,
  message?: string,
) {
  const reg
    = /^[\w.!#$%&'*+/=?^`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,200}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,200}[a-z0-9])?)*$/i

  if (!value) {
    return callback(message || '请输入邮箱')
  }
  if (!reg.test(value)) {
    callback(message || '邮箱格式错误')
  }
}
